package com.zpark;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * @PackageName: com.zpark
 * @ClassName: DOMQueryXmlFileDemo
 * @Description: DOM解析器-查询
 * @author: RZS
 * @date: 2021/8/15  14:12
 */
public class DOMQueryXmlFileDemo {
    public static void main(String[] args) throws Exception {
        // 获取xml文件对应的路径
        String path = DOMQueryXmlFileDemo.class.getClassLoader().getResource("dom-select.xml").getPath();
        // 由于此次路径中含有中文，所以需要进行解码
        path = URLDecoder.decode(path, "utf-8");
        // 获取DocumentBuilderFactory对象
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        // 根据DocumentBuilderFactory对象,构建DocumentBuilder对象
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // 根据DocumentBuidler对象,构建Document对象
        Document document = documentBuilder.parse(path);
        // 根据标签名获取所有标签节点集合nodeList
        NodeList nodeList = document.getElementsByTagName("supercars");
        for (int i = 0; i < nodeList.getLength(); i++) {
            // 循环获取每一个节点对象
            Node node = nodeList.item(i);
            System.out.println("标签名字："+node.getNodeName());
            // 将node转换为element
            Element element = (Element) node;
            System.out.println("获取属性company对应的值："+element.getAttribute("company"));
            // element根据标签名获取对象
            System.out.println("--------------------------------------------");
            NodeList elements = element.getElementsByTagName("carname");
            for (int i1 = 0; i1 < elements.getLength(); i1++) {
                Node item = elements.item(i1);
                Element elm = (Element)item;
                System.out.println(elm.getTextContent());
            }

        }

    }
}
